package com.secsbrain.development.feign;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Map;

/**
 * Factory for SpringLoadBalancer instances that caches the entries created.
 *
 * @author zhaoyi
 */
public class SbCachingSpringLoadBalancerFactory {

    protected final SpringClientFactory factory;
    protected LoadBalancedRetryFactory loadBalancedRetryFactory = null;

    private Map<String, Sb2FeignLoadBalancer> cache = new ConcurrentReferenceHashMap<>();

    public SbCachingSpringLoadBalancerFactory(SpringClientFactory factory) {
        this.factory = factory;
    }

    public SbCachingSpringLoadBalancerFactory(SpringClientFactory factory,
                                            LoadBalancedRetryFactory loadBalancedRetryPolicyFactory) {
        this.factory = factory;
        this.loadBalancedRetryFactory = loadBalancedRetryPolicyFactory;
    }

    public Sb2FeignLoadBalancer create(String clientName) {
        Sb2FeignLoadBalancer client = this.cache.get(clientName);
        if (client != null) {
            return client;
        }
        IClientConfig config = this.factory.getClientConfig(clientName);
        ILoadBalancer lb = this.factory.getLoadBalancer(clientName);
        ServerIntrospector serverIntrospector = this.factory.getInstance(clientName,
                ServerIntrospector.class);
        //retry的后面再说
        client = new Sb2FeignLoadBalancer(lb, config, serverIntrospector);
        this.cache.put(clientName, client);
        return client;
    }

}
